package org.example.flow;

import javax.swing.*;
import java.awt.*;
import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;

/**
 * flow流
 * <p>jdk自带的响应式流</p>
 */
public class Demo1 {
    public static void main(String[] args) throws InterruptedException {
        //创建流发布
        try (SubmissionPublisher<Integer> publisher = new SubmissionPublisher<>()) {
            //订阅流
            publisher.subscribe(component());
            //修改数据(这步会刷新订阅者实际,已达到响应式视图的功能)
            for (int i = 10; i >= 0; i--) {
                Thread.sleep(1000);
                publisher.submit(i);
            }
        }
    }

    //订阅组件,该组件和前端sse的订阅方式一致,使用回调方式,不需要协程或多线程程监听
    public static <T> Flow.Subscriber<T> component() {
        return new Flow.Subscriber<>() {
            final JLabel label = new JLabel("");
            private Flow.Subscription subscription;

            //订阅回调
            @Override
            public void onSubscribe(Flow.Subscription subscription) {
                this.subscription = subscription;
                this.subscription.request(Long.MAX_VALUE);
                //窗口
                JFrame frame = new JFrame("响应式例子");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(300, 200);
                //文本
                frame.add(label, BorderLayout.CENTER);
                frame.setVisible(true);
            }

            //获取到内容回调
            @Override
            public void onNext(T item) {
                //设置文本
                label.setText(item + "");
                //再次请求
                this.subscription.request(1);
            }

            @Override
            public void onError(Throwable throwable) {
            }

            @Override
            public void onComplete() {
            }
        };
    }
}
